﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FacturIT.Service.WorkingHour;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Factur_IT.WorkingHour
{
    public partial class generateInvoice : System.Web.UI.Page
    {
        int companyid;
        int projectid;
        int companyprojectid;

        DateTime van;
        DateTime tot;

        protected void Page_Load(object sender, EventArgs e)
        {
            bool loggedIn = FacturIT.Service.FacturITManager.Instance.IsLoggedID();

            if (loggedIn != true)
                Response.Redirect("~/Account/login.aspx");

            projectid = Convert.ToInt32(Request.Params["ProjectID"]);
            companyid = Convert.ToInt32(Request.Params["CompanyID"]);


        }

        protected void btnInvoice_Click(object sender, EventArgs e)
        {
            using (Document doc = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
                doc.Open();

                //header
                Rectangle page = doc.PageSize;
                PdfPTable head = new PdfPTable(1);
                head.TotalWidth = page.Width;
                Phrase phrase = new Phrase(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",new Font(Font.FontFamily.COURIER, 8));
                PdfPCell c = new PdfPCell(phrase);
                c.Border = Rectangle.NO_BORDER;
                c.VerticalAlignment = Element.ALIGN_TOP;
                c.HorizontalAlignment = Element.ALIGN_CENTER;
                head.AddCell(c);
                head.WriteSelectedRows(
                                        // first/last row; -1 writes all rows
                                      0, -1,
                                        // left offset
                                      0,
                                        // ** bottom** yPos of the table
                                      page.Height - doc.TopMargin + head.TotalHeight + 20,
                                      writer.DirectContent
                                    );

                /* add image
                 Image gif = Image.GetInstance(Request.MapPath("~/kyouyuu/image/kuujinbo2.gif"));
                 gif.Alignment = Image.MIDDLE_ALIGN;
                // downsize the image by specified percentage        
                    gif.ScalePercent(50f);
                    doc.Add(gif);
                 */
                Paragraph hoofding = new Paragraph();
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).CompanyName +" \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).Street + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).PostalCode + " " + FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).City + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).Country + " \n");
                hoofding.Add(FacturIT.Service.FacturITManager.Instance.ReadCompany(companyid).CompanyPhone + " \n");

                doc.Add(hoofding);

                Paragraph datum = new Paragraph(DateTime.Today.ToString().Split(' ')[0]);
                datum.Alignment = 2;
                doc.Add(datum);

                Paragraph p = new Paragraph("Werkuren periode " + calVan.SelectedDate.ToString().Split(' ')[0] + " - " + calTot.SelectedDate.ToString().Split(' ')[0]);
                    p.Alignment = 1;
                    doc.Add(p);
                // table data, see code snippet following this one
                    doc.Add(HoursTable());

                   
                Paragraph totaal = new Paragraph();
                TimeSpan totaalUren = TimeSpan.Zero;
                foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllWorkingHoursFromUserProjectInPeriodCharged(companyprojectid, van, tot))
                {
                    totaalUren += item.WorkingTime;
                } 
                totaal.Alignment = 2;
                totaal.Add(totaalUren.ToString());
                doc.Add(totaal);


                doc.Close();
            }
        }
        private PdfPTable HoursTable() 
        {
          string[] col = { "Van", "Tot", "Aantal uren" };
          PdfPTable table = new PdfPTable(3);
        /*
        * default table width => 80%
        */  
          table.WidthPercentage = 100;
        // then set the column's __relative__ widths
          table.SetWidths(new Single[] {2, 2, 2});
        /*
        * by default tables 'collapse' on surrounding elements,
        * so you need to explicitly add spacing
        */
          table.SpacingBefore = 10;

          for (int i = 0; i < col.Length; ++i) 
          {
            PdfPCell cell = new PdfPCell(new Phrase(col[i]));
            cell.BackgroundColor = new BaseColor(204, 204, 204);
            table.AddCell(cell);
          }

        // !! database code omitted !!
        // r.Read is the DbDataReader for whatever flavor 
        // of database you're connecting to; we're iterating
        // over the results returned from the database and 
        // adding rows to the table in the PDF 

          List<WorkingHourDTO> werkuren = new List<WorkingHourDTO>();

          //int companyid = Convert.ToInt32(Session["UserID"]);
          //int projectid = Convert.ToInt32(Request.Params["ProjectID"]);
          companyprojectid = FacturIT.Service.FacturITManager.Instance.ReadCompanyProjectByProjectAndCompany(projectid, companyid).CompanyProjectID;

          van = calVan.SelectedDate;
          tot = calTot.SelectedDate;

          foreach (var item in FacturIT.Service.FacturITManager.Instance.ReadAllWorkingHoursFromUserProjectInPeriodAndSetCharged(companyprojectid, van, tot))
            {
                table.AddCell(item.Starttime.ToString().Split(' ')[0]);
                table.AddCell(item.Endtime.ToString().Split(' ')[0]);
                table.AddCell(item.WorkingTime.ToString());
            }
            return table;
          }
    }
}